//声明构造函数
function Promise(executor) {
    //添加属性
    this.PromiseState = 'pending'
    this.PromiseResult = null
    //声明属性
    this.callbacks = []
    //保存实例对象的this值
    const that = this;

    //resolve函数
    function resolve(data) {
        //判断状态
        if (that.PromiseState !== 'pending') return;
        //1.修改对象的状态(promiseState)
        that.PromiseState = 'fulfilled'
        //2.设置对象结果值(promiseResult)
        that.PromiseResult = data
        //执行回调
        that.callbacks.forEach(item => {
            item.onResolved(data)
        })
    }
    //reject函数
    function reject(data) {
        //判断状态
        if (that.PromiseState !== 'pending') return;
        //1.修改对象的状态(promiseState)
        that.PromiseState = 'rejected'
        //2.设置对象结果值(promiseResult)
        that.PromiseResult = data
        //执行回调
        that.callbacks.forEach(item => {
            item.onRejected(data)
        })
    }

    try {
        //同步调用【执行器函数】
        executor(resolve, reject)
    } catch (e) {
        reject(e)
    }


}

//添加then方法
Promise.prototype.then = function (onResolved, onRejected) {
    //调用回调函数
    if (this.PromiseState === 'fulfilled') {
        onResolved(this.PromiseResult)
    }
    if (this.PromiseState === 'rejected') {
        onRejected(this.PromiseResult)
    }
    //判断pending状态
    if (this.PromiseState === 'pending') {
        //保存回调函数
        this.callbacks.push({
            onResolved: onResolved,
            onRejected: onRejected
        })
    }
}